package com.situ.ssh.dao.impl;

import com.situ.ssh.common.ServerResponse;
import com.situ.ssh.dao.IUserDao;
import com.situ.ssh.entity.SearchCondition;
import com.situ.ssh.entity.User;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements IUserDao {

    public User login(User user) {
        String sql = "FROM User u WHERE u.name=? AND u.password=?";
        List<User> list = (List<User>) getHibernateTemplate().find(sql, user.getName(), user.getPassword());
        if (list != null && list.size() > 0) {
            return  list.get(0);
        }
        return null;
    }

    @Override
    public ServerResponse pageList(SearchCondition searchCondition) {
        Integer page = searchCondition.getPage();
        Integer limit = searchCondition.getLimit();
        DetachedCriteria detachedCriteria = searchCondition.getDetachedCriteria();
        // 查询total：总记录数（带着条件查询出来的总记录数）
        detachedCriteria.setProjection(Projections.rowCount());// 要查询的总记录数
        List<?> list = getHibernateTemplate().findByCriteria(detachedCriteria);
        Long count = (Long) list.get(0);
        // 得到当前页的数据
        detachedCriteria.setProjection(null);
        List<User> rows = (List<User>) getHibernateTemplate().findByCriteria(detachedCriteria, (page - 1) * limit, limit);
        return ServerResponse.createSuccess("查找成功", (int)count.longValue(), rows);
    }
}
